<template>
  <view class="component-box">
    <view
      class="classify-section"
      :style="[classifyCss]"
      :class="styleType == 2 ? 'flex-layout' : ''"
      v-if="classifyList.length"
    >
      <div class="left-hold-place" v-if="styleType == 2">
        <div
          class="tab-item"
          v-for="(item, index) in classifyList"
          :key="index"
        ></div>
      </div>
      <view class="classify-header" :style="[goodsTabCss]">
        <view :style="[moduleBgCss]" class="module-bg"></view>
        <u-sticky
          @fixed="showStickyView = true"
          @unfixed="showStickyView = false"
          :offset-top="stickyOffTop"
          :h5-nav-height="0"
        >
          <view
            v-if="height && showStickyView"
            :style="{
              height: height + 'px'
            }"
          ></view>
          <view :style="{ backgroundColor: moduleBgCss.backgroundColor + ' !important' }">
            <!-- 默认样式tab -->
            <defaultTab
              v-if="styleType == 1 && tabStyle == 1"
              :classifyList="classifyList"
              :activeTab="activeTab"
              :propsData="propsData"
              @changeTab="changeTab"
            ></defaultTab>
            <!-- 带副标题的tab -->
            <subtitleTab
              v-if="styleType == 1 && (tabStyle == 2 || tabStyle == 3)"
              :classifyList="classifyList"
              :activeTab="activeTab"
              :propsData="propsData"
              @changeTab="changeTab"
            ></subtitleTab>
            <!-- 左侧tab -->
            <leftTab
              v-if="styleType == 2"
              :classifyList="classifyList"
              :activeTab="activeTab"
              :propsData="propsData"
              @changeTab="changeTab"
            ></leftTab>
          </view>
        </u-sticky>
      </view>
      <view class="classify-body" :style="[goodsListCss]">
        <view :style="[goodsBgCss]" class="module-bg"></view>
        <!-- 样式1 -->
        <defaultTem
          v-if="goodsType == 1"
          :propsData="propsData"
          :goodsList="goodsList"
          :goodsItemSpace="goodsItemSpace"
          @clickBuyBtn="clickBuyBtn"
          @toGoodDetail="toGoodDetail"
        ></defaultTem>
        <!-- 样式2 -->
        <flexTwoTem
          v-if="goodsType == 2"
          :propsData="propsData"
          :goodsList="goodsList"
          :goodsItemSpace="goodsItemSpace"
          @clickBuyBtn="clickBuyBtn"
          @toGoodDetail="toGoodDetail"
        ></flexTwoTem>
        <!-- 样式3 -->
        <columnTem
          v-if="goodsType == 3"
          :propsData="propsData"
          :goodsList="goodsList"
          :goodsItemSpace="goodsItemSpace"
          @clickBuyBtn="clickBuyBtn"
          @toGoodDetail="toGoodDetail"
        ></columnTem>
        <!-- 样式4 -->
        <flexGroupTem
          v-if="goodsType == 4"
          :propsData="propsData"
          :goodsList="goodsList"
          :goodsItemSpace="goodsItemSpace"
          @clickBuyBtn="clickBuyBtn"
          @toGoodDetail="toGoodDetail"
        ></flexGroupTem>
      </view>
    </view>

    <!-- 添加购物车数组 -->
    <goodsAddCart :good="goodsOfAdd"></goodsAddCart>
  </view>
</template>

<script>
import { diyMixin } from "../mixins/diy";
import goodsAddCart from "../goodsAddCart/index.vue";
import defaultTem from "../productShow/templates/defaultTem.vue";
import flexTwoTem from "../productShow/templates/flexTwo.vue";
import columnTem from "../productShow/templates/column.vue";
import flexGroupTem from "../productShow/templates/flexGroup.vue";
import defaultTab from "./templates/defalut.vue";
import subtitleTab from "./templates/subtitleTab.vue";
import leftTab from "./templates/leftTab.vue";
import { mapGetters } from "vuex";
export default {
  props: {
    propsData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    loadMoreProductClassify: {
      type: Boolean,
      default: false
    }
  },
  components: {
    defaultTem,
    flexTwoTem,
    columnTem,
    flexGroupTem,
    goodsAddCart,
    defaultTab,
    subtitleTab,
    leftTab
  },
  mixins: [diyMixin], //混入文件
  watch: {
    loadMoreProductClassify(val) {
      if (val) {
        this.scrollToEnd();
      }
    },
    getIndexSearchHeight: {
      handler(e) {
        let hasSearchTop = uni.getStorageSync("hasSearchTop");
        if (hasSearchTop === 1) {
          this.height = e;
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      height: 0,
      activeTab: 0,
      goodsList: [],
      goodsOfAdd: {}, // 添加到购物车的商品
      currentTab: {},
      selectArr: [],
      page: 1,
      pageSize: 10,
      row_count: 0,
      classifyList: [],
      showStickyView: false //是否显示吸顶组件占位
    };
  },
  computed: {
    ...mapGetters(["getIndexSearchHeight"]),
    styleType() {
      return this.propsData.params.styleType;
    },
    goodsType() {
      return this.propsData.params.goodsType;
    },
    type() {
      return this.propsData.params.type;
    },
    goodsItemSpace() {
      let out = this.propsData.params.goodsItemOutSpace || "0";
      let inner = this.propsData.params.goodsItemInnerSpace || "0";
      let goodsType = this.propsData.params.goodsType || 1;
      let css = {};
      out = out * 2;
      inner = inner * 2;
      if (out) {
        if (goodsType == 1) {
          css["margin"] = `0 0 ${out}rpx 0`;
        }
        if (goodsType == 3) {
          css["margin"] = `0 ${out}rpx ${out}rpx ${out}rpx`;
        }
        if (goodsType == 2 || goodsType == 4) {
          css["margin"] = `0 ${out}rpx ${out}rpx 0`;
        }
      }
      if (inner) {
        css["padding"] = `${inner}rpx`;
      }
      return css;
    },
    stickyOffTop() {
      let top = 0;
      top = this.statusBarHeight * 2 + 88 - 4;

      return top.toString();
    },
    tabStyle() {
      return this.propsData.params.tabStyle || "1";
    },
    tabSectionBg() {
      if (this.styleType == 2)
        return { backgroundColor: this.propsData.params.leftTabBg };
      return "";
    },
    goodsTabCss() {
      if (!this.propsData) return {};
      let style = Object.assign({}, this.propsData.moduleCss);
      if (style.margin) style.margin = `0 0 ${style.margin * 2}rpx 0`;
      if (style.padding) style.padding = `0 ${style.padding * 2}rpx`;
      if (style.borderRadius)
        style["borderRadius"] = `${style.borderRadius * 2}rpx`;
      let obj = {
        margin: style.margin,
        borderRadius: style.borderRadius,
        padding: style.padding,
        position: "relative",
        overflow: "hidden"
      };
      if (this.styleType == 2) {
        obj["backgroundColor"] = this.propsData.params.leftTabBg;
      }
      return obj;
    },
    classifyCss() {
      if (!this.propsData.params?.goodsBgCss) return {};
      let style = Object.assign({}, this.propsData.params.goodsBgCss);
      if (style.borderRadius)
        style["borderRadius"] = `${style.borderRadius * 2}rpx`;
      let obj = {
        borderRadius: style.borderRadius,
        position: "relative",
        overflow: "hidden"
      };
      return obj;
    },
    goodsListCss() {
      if (!this.propsData.params?.goodsBgCss) return {};
      let style = Object.assign({}, this.propsData.params.goodsBgCss);
      if (style.margin) style.margin = `0 0 ${style.margin * 2}rpx 0`;
      if (style.padding) style.padding = `0 ${style.padding * 2}rpx`;

      let obj = {
        margin: style.margin,
        borderRadius: style.borderRadius,
        padding: style.padding,
        position: "relative",
        overflow: "hidden"
      };
      return obj;
    },
    goodsBgCss() {
      if (!this.propsData.params?.goodsBgCss) return {};
      let style = Object.assign({}, this.propsData.params.goodsBgCss);

      if (!style.useBackground) {
        return {
          background: "inherit"
        };
      }
      let hSpace = style.padding;
      if (hSpace) {
        style["width"] = `calc(100% - ${hSpace * 4}rpx)`;
        style["left"] = hSpace * 2 + "rpx";
      }
      return style;
    }
  },
  filters: {},
  mounted() {
    this.filterSelectData();
  },
  methods: {
    // 筛选出商品id数组
    async filterSelectData() {
      let { type } = this,
        classifyList = [];

      classifyList = this.propsData.params.classifyList;
      this.classifyList = classifyList;

      let [item] = this.classifyList.filter((d, index) => {
        return this.activeTab == index;
      });
      if (!item) return;
      this.currentTab = item;
      if (item && item.dataFrom == "select") {
        item.data.forEach((d) => {
          this.selectArr.push(d.id);
        });
      }

      this.initProductData();
    },

    initProductData(type = "") {
      let params = {};

      if (
        this.currentTab.dataFrom == "classify" ||
        this.propsData.params.type == 2
      ) {
        params = {
          cat_id: this.currentTab.classifyId,
          page: this.page,
          limit: this.pageSize
        };
      } else {
        params = {
          goods_id: this.selectArr
            .slice((this.page - 1) * 10, this.page * 10)
            .join(",")
        };
      }

      if (type) {
        params["isLoadMore"] = true;
      }
      if (this.currentTab.dataFrom) {
        this.getProducts(params);
      }
    },
    // api获取商品数据
    async getProducts(params) {
      const res = await this.$allrequest.diy.getGoodsList(params);
      if (res.code == 0) {
        if (this.currentTab.dataFrom == "classify") {
          this.row_count = res.data.row_count;
        }
        if (params.isLoadMore) {
          this.goodsList = [...this.goodsList, ...res.data.list];
        } else {
          this.goodsList = res.data.list;
        }
      }
    },
    // 切换tab
    changeTab(e) {
      let { item, index } = e;
      this.activeTab = index;
      this.currentTab = item;
      this.selectArr = [];
      this.page = 1;
      if (!item.classifyId && !item.data) {
        this.goodsList = [];
        return;
      }

      const query = uni.createSelectorQuery().in(this);
      query
        .select(".classify-header")
        .boundingClientRect((data) => {
          let top = 0;
          if (data.top <= 0) {
            top = 0;
          } else {
            top = data.top;
          }
          this.$emit("classifyToTop", { nodeTop: data.top });
        })
        .exec();

      this.filterSelectData();
    },
    // 点击添加购物车按钮回调
    clickBuyBtn(e) {
      console.log('添加到购物车的数据',e)
      let item = e.item;
      if (item.product_type != 0 && item.product_type != 4) return;
      let goods = Object.assign({}, item);
      this.goodsOfAdd = goods;
      setTimeout(() => {
        this.goodsOfAdd = {};
      }, 1);
    },
    // 跳转商品详情
    toGoodDetail(e) {
      if (!e) return;
      let id = e.id;
      uni.navigateTo({
        url: "/goods/goods/goods?id=" + id
      });
    },
    scrollToEnd() {
      if (
        this.page * this.pageSize >= this.row_count &&
        this.currentTab.dataFrom == "classify"
      )
        return;

      if (
        this.currentTab.dataFrom == "select" &&
        this.page * this.pageSize >= this.selectArr.length
      )
        return;
      this.page++;
      this.initProductData("more");
    }
  }
};
</script>

<style scoped lang="scss">
.component-box {
  width: 100%;
  position: relative;
  .classify-section {
    width: 100%;
    .classify-header {
      width: 100%;
      position: relative;
    }
    .classify-body {
      padding-bottom: 2.67vw;
      position: relative;
      .classify-goods {
        width: 100%;
        height: 1px;
      }
    }
  }
  .flex-layout {
    position: relative;
    overflow: hidden;
    clear: both;
    .classify-header {
      width: 21.33vw;
      height: 100%;
      position: absolute !important;
      left: 0;
      top: 0;
      background-color: #ffffff;
    }
    .left-hold-place {
      width: 21.33vw;
      clear: both;
      float: left;
      padding-top: 20px;
      overflow: hidden;
      .tab-item {
        width: 100%;
        height: 12vw;
      }
    }
    .classify-body {
      width: 78.67vw;
      padding-top: 2.93vw;
      float: right;
    }
  }

  .module-bg {
    width: 100%;
    height: 100%;
    z-index: -1;
    position: absolute;
    left: 0;
    top: 0;
  }
}
</style>
